define(function (require) {
var zsApp = require('app');
require('roleby');
//require('rolebyrole');
//require('rolebyuser');
require('zTree');
require('jqueryForm');
require('lodash');


zsApp.controller( 'userRoleController',["$scope", "$http", "$state","$rootScope","$cookieStore", "$timeout","promptCache",function( $scope,$http, $state,$rootScope,$cookieStore,$timeout,promptCache){
	// 默认关闭弹窗
	$(".modal-backdrop").remove();
	// 储存角色ID
	$scope.roleId = [];
	// 储存角色组ID
	$scope.roleGroupId = []
	
	//active
	$scope.userrole = true;
	//自动分配
	$scope.arr = [];
	$scope.autoAssignmentList = [{"id":0,"name":"不是"},{"id":1,"name":"是"}];

	// 分页
	function dataRendering() {
		$scope.paginationConf = {
	        currentPage    : 1,
	        totalItems     : 100,
	        itemsPerPage   : 20,
	        pagesLength    : 15,
	        perPageOptions : [10, 20, 30, 40, 50],
	        onChange: function(){
	        	var self = this;
	        	var pagingData = {
	        		pageNumber  : self.currentPage,  
					pageSize 	: self.itemsPerPage,  
	        	}
	        	//console.log(pagingData.pageNumber);
	        	if( (($scope.isRequestCurrentPage != self.currentPage) || ($scope.isRequestItemsPerPage != self.itemsPerPage)) && (new Date() - $scope.nowTime > 500) )
	        	{	
	        		$scope.nowTime = new Date();
					$http({
						url    : $scope.zsUrl+'digitalhome-boss/admin/roles/getList',
						method : 'POST',
						data   : {
							pageNumber  : self.currentPage,  
							pageSize 	: self.itemsPerPage, 
							queryType   :  	0,
						}
					}).then(function success(res) {
						//console.log(res);
						
							if( '0000' == res.data.result_code ){
								// 角色组列表页面表格
								$scope.tabVal = res.data.result;
								
								
								// 遍历所有角色ID
								angular.forEach(res.data.result, function(obj, i) {
                    				$scope.roleId[i] = obj.roleId;
									$scope.roleGroupId[i] = obj.roleGroupId;
                				});
								$scope.tabVal.roleGroupName = $scope.roleGroupList.roleGroupId;
								$cookieStore.put('roledate',$scope.tabVal);
								//console.log($scope.tabVal)
								// 总共有多少条数据
								self.totalItems = res.data.length;
							}else{
								$scope.isNoData = false;
                    			return false;
							}
							//console.log($scope.tabVal);
						}, 
						function error(err) {
							$scope.isNoData = false;
							console.log(err);
						}
					);
					$scope.isRequestCurrentPage = self.currentPage;
					$scope.isRequestItemsPerPage = self.itemsPerPage;
				}
	        }
	    }
    }
    dataRendering();
    
    //查询角色组列表
	$scope.roleGroupList = [];
	//查询角色组列表
	$http({
		url      : $scope.zsUrl+'digitalhome-boss/admin/roles/getRoleGroupsList',
		method   : 'POST',
	}).then(function success(res) {
		angular.element(res.data.result).each(function(i) {
			$scope.arr = { id: res.data.result[i].roleGroupId, roleGroupName: res.data.result[i].roleGroupName};
			$scope.roleGroupList.push($scope.arr); 					
			$scope.roleGroupId[i] = this.roleGroupId;
		});
		//console.log($scope.roleGroupList.id);
		$scope.roleGroupName233 = $scope.updateroleGroupId;

	},function error(err){
		console.log(err);
	});

	$scope.roleGroupSelect = function() {
	  	$scope.thisRoleGroupName = $scope.role_roleGroupName;
	  	console.log($scope.thisRoleGroupName);
	}
	
	// 确定新增（新增一条角色组列表数据）
	$scope.confirmNewlyAdded = function($event, $index) {  
		var roleAddData = {
          	roleName       : $scope.role_roleName,
          	roleGroupId	   : $scope.thisRoleGroupName,
          	description    : $scope.role_description,
			autoAssignment : $scope.role_autoAssignment,
			createUserId   : $scope.role_createUserId
		}
		$http({
			url      : $scope.zsUrl+'digitalhome-boss/admin/roles/add',
			method   : 'POST',
			data     : JSON.stringify(roleAddData),/* 将JSON发送给服务器 */
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', 
		}).then(function success(res) {
			//console.log(res.status);
			// 操作提示
			if( '0000' == res.data.result_code ){
				promptCache.successPrompt(res.data.message);
				$state.go("user.role",{},{reload:true});
				$("#add").modal("hide");
			}else{
				promptCache.errorPrompt(res.data.message);
			}
		},
		function error(err){
			console.log(err);
		});	
	}
		
	//
	$scope.getroleGroupID = function(){
		//console.log($scope.role_roleGroupName);
	}

	// 详情（用于向用户展示从服务器获取的数据）
	$scope.details = function( $index) {
		//console.log($scope.roleId[$index]);
		console.log($index);
		$("#details").modal("show");
		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/roles/getRolesInfo/'+$scope.roleId[$index]+'',
			method : 'GET',
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', 
		}).then(function success(res){

			// 向用户展示从服务器获取到的数据
			$scope.roledetails = res.data.result;
            $scope.roledetails.roleGroupName = $scope.roledetails.roleGroupId;
			$scope.roleGroupList.roleGroupName = $scope.roleGroupList.id;
			//console.log($scope.roleGroupList)
			//console.log($scope.roledetails)

		},function error(err){
			console.log(err);
		});
	}


	// 权限详情列表（用于向用户展示从服务器获取的数据）
	$scope.permissionAssignment = function( $index) {
		
		$("#permissionAssignment").modal("show");
		
		 var operation_code = [];
		 var permissionAll = [];
		 
		 $scope.roleID = $scope.roleId[$index];
		 
		$http
        ({
            url     :$scope.zsUrl+'digitalhome-boss/user/functions/getRolePermissionList/'+$scope.roleId[$index]+'',  
            method  : 'POST',
            
        }).success(function(res) {

            angular.forEach(res.result, function(obj, i) {
            	operation_code[i] = obj.operation_id+":"+obj.functionId;
            });
            
            $http({
    			url    : $scope.zsUrl+'digitalhome-boss/user/functions/getPermissionList/',
    			method : 'GET',
    			dataType : 'json',
    			contentType : 'application/json;charset=UTF-8', 
    			}).success(function(res) {

    				//$scope.res = res.result;
    				$scope.selectedData = operation_code;	
    				
    				var result = angular.fromJson(res.result); 			
    				
    				for(var j = 0;j<result.length;j++){ 					
    					
    					if(result[j].permissionListes!=null || result[j].permissionListes!=""){
    						
    						var permission = result[j].permissionListes.split(",");
    						
    						for(var i=0;i<permission.length;i++){

    							var permissionId = permission[i].split(":");
    							
    							permissionAll.push(permissionId[0]+":"+result[j].id);
	
    						}	
    					}

    				}

    				$scope.res = permissionAll;

    				var zTree;
    				var demoIframe;

    				var setting = {
    					view: {
    						addDiyDom: addDiyDom
    					},
    					data: {
    						simpleData: {
    							enable: true,
    							idKey: "id",
    							pIdKey: "pId",
    							rootPId: 0
    						},
    						key: {
    							checked: "isChecked"
    						}
    					},
    					
    				};
    		
    				// 动态在节点后面添加按钮
    				function addDiyDom(treeId, treeNode) {

    					var aObj = $("#" + treeNode.tId + "_a");
    					
    					if ($("#diyBtn_"+treeNode.id).length>0) return;
    			
    					// 拆分权限列表 存放数组
    					if(treeNode.permissionListes!=null){
    						
    						var treeCh = [];

    					    var permissArr = treeNode.permissionListes.split(",");

    						for(var i=0;i<permissArr.length ; i++ ){
    							   								
    							var permiss = permissArr[i].split(":");
    							
    							var editStrs;
    														
    							var tempPermiss = permiss[0]+":"+treeNode.id;

    							// 找到 ，存在
    							if(operation_code.indexOf(tempPermiss) != -1){
    											
    								$scope.selectedData.push(tempPermiss);
    								
    								 editStrs = "<input type='checkbox'  checked='checked'  onclick='fnIsChecked(this)'  value="+permiss[0]+":"+treeNode.id+">"+  permiss[1];
    								  								
    							}else{
    																
    								 editStrs = "<input type='checkbox'    onclick='fnIsChecked(this)'  value="+permiss[0]+":"+treeNode.id+">"+  permiss[1];
    									
    							}
    							
    						    treeCh.push(editStrs);  						
    					   }
    						    	
    					aObj.append(treeCh.toString().replace(","," "));
    					
    					var btn = $("#diyBtn_"+treeNode.id);
    					
    					if (btn) btn.bind("click", function(){alert("diy Button for " + treeNode.name);});
    					
    				   };
    				   
    				}	
    				var treeObj = $("#tree");
    				
    				treeObj = $.fn.zTree.init(treeObj, setting, res.result);
    				
    				treeObj.expandAll(true); 

    				//取得所有节点
    				var nodes = treeObj.getNodes();
    			
    		}).error(function(err) {
    			console.log(err);
    		});
            
        }).error(function(err) {
            console.log(err);
        });

	}
	


	// 修改（调用接口与“详情”相同，用于向用户展示从服务器获取的数据）
	$scope.edit = function($event, $index) {
		var indexs = $index;
		//console.log($index);
		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/roles/getRolesInfo/'+$scope.roleId[$index]+'',
			method : 'GET',
		}).then(function success(res) {
				//console.log(res.data.result);
				// 向用户展示从服务器获取到的数据
				$scope.roleupdate = {
					roleId  		: res.data.result.roleId ,
					roleGroupId     : res.data.result.roleGroupId,
					roleName 		: res.data.result.roleName,
					autoAssignment 	: res.data.result.autoAssignment,
	              	description 	: res.data.result.description,
             	 }
				 $cookieStore.put('roleGroupId',$scope.roleupdate.roleGroupId);	
				 $scope.updateroleGroupId= $cookieStore.get('roleGroupId');
              	// 选中默认的值
              	//console.log($scope.updateroleGroupId);
              	$cookieStore.put('roleupdate',$scope.roleupdate);
				$state.go("user.roleupdate",{},{reload:true});
		},function error() {
			console.log(err);
		});
	}

	// role-selected
	$scope.rolechoose = [];  
    var rolesupdateSelected = function(action,roleId){  
        if(action == 'add' && $scope.rolechoose.indexOf(roleId) == -1){  
            $scope.rolechoose.push(roleId);  
        }
        if(action == 'remove' && $scope.rolechoose.indexOf(roleId)!=-1){  
            var idx = $scope.rolechoose.indexOf(roleId);  
            $scope.rolechoose.splice(idx,1);   
        }  
    }  
    $scope.rolesupdateSelection = function($event,roleId,tabVal){  
        var checkbox = $event.target;  
        var action = (checkbox.checked?'add':'remove');  
        rolesupdateSelected(action,roleId); 
        console.log($scope.rolechoose);
      
    }  
    $scope.rolesisSelected = function(id,val){  
        return $scope.rolechoose.indexOf(id)>=0;  
    } 
    $scope.all = function(tabVal){
    	$scope.rolechoose = []; 
    	if($scope.userall == true){
        	$scope.userall = true;
        	angular.forEach(tabVal, function (i, index) {
                $scope.rolechoose.push(i.roleId); 
           })
        	console.log($scope.rolechoose);
        }else{
        	$scope.userall = false;
        	$scope.rolechoose =[];
        	console.log($scope.rolechoose);
        }
    }

	// 删除（保存当前点击对象的$index、this指向）
	var _this = '', _index = 0;
	$scope.deletes = function($event, $index) {
		// 当前对象（this指向不变）
		_this = angular.element($event.target);
		// 每一行的序列号
		_index = $index;
		if($scope.rolechoose == ""){
			promptCache.prompt("请选中你要删除的数据！");
		}else{
			$("#delete").modal('show');
		}
		console.log($scope.rolechoose);
	}

	// 确定删除（用于用户删除数据）
	$scope.confirmDel = function($event) {
		var rolechoosedate = {
			roleId : $scope.rolechoose,
		}
		//console.log(rolechoosedate);
		$http({
			url: $scope.zsUrl+'digitalhome-boss/admin/roles/batchDelete',
			method: 'POST',
			data: JSON.stringify(rolechoosedate), /* 给服务器发送需要删除的数据对应的ID */
		}).then(function success(res) {
				console.log(rolechoosedate);
				// result_code == '0000' 则删除，否则不删除
				if( '0000' == res.data.result_code )
				{
					_this.parents('tr').remove();
					promptCache.successPrompt(res.data.message);
				}
				else 
				{
					console.log(res.data);
				}
			},
			function error(err) {
				console.log(err);
			}
		);

	}
	

	$scope.roledetailsblock = function(){
		$cookieStore.remove('$scope.roledetails');
		$state.go("user.roles",{},{reload:true});
	}
	
	// 确认修改（用于用户修改原有的数据）
	$scope.confirmEdit = function($event,$index) {
		// 修改角色组名、描述（封装成JSON）
		var editData = {
			roleId  	  : $scope.roleupdatenew.roleId,
			roleGroupId   : $scope.roleupdatenew.roleGroupName,
			roleName      : $scope.roleupdatenew.roleName,
			//roleGroupName : $scope.roleupdatenew.roleGroupName,
			autoAssignment: $scope.roleupdatenew.autoAssignment,
			description   : $scope.roleupdatenew.description
		}
		console.log($scope.roleupdatenew.roleGroupName);
		$http({
			url   	: $scope.zsUrl+'digitalhome-boss/admin/roles/modify',
			method  : 'POST',
			data    : editData, /* 将JSON发送给服务器 */
		}).then(function success(res) {
			console.log(editData );
			$state.go("user.role",{},{reload:true});
			// 重新加载页面
			if( '0000' == res.data.result_code ){
				promptCache.successPrompt(res.data.message);
			}else{
				promptCache.errorPrompt(res.data.message);
			}
		},function error(err) {
			console.log(err);
		});
	}
	
	//Online editing
	$scope.tabVal = $cookieStore.get('roledate');
	var dummydata = $scope.tabVal;
	$scope.role_focus = function($index){
		function rolesupdate(){
			var roledate = {
				roleId		  : $scope.tabVal[$index].roleId,
				roleName	  :	$scope.tabVal[$index].roleName,
				roleGroupId   : $scope.tabVal[$index].roleGroupId,
				description   : $scope.tabVal[$index].description,
				autoAssignment: $scope.tabVal[$index].autoAssignment,
			}
			$http({
				url   	: $scope.zsUrl+'digitalhome-boss/admin/roles/modify',
				method  : 'POST',
				data    : roledate, /* 将JSON发送给服务器 */
			}).then(function success(res){
				console.log($scope.tabVal[$index]);
				console.log(roledate);
				// 重新加载页面
				
				if( '0000' == res.data.result_code ){
					promptCache.successPrompt("修改角色成功","user.roles");
					var dummydata = $scope.tabVal;
				}else{
					promptCache.successPrompt(res.data.message);	
				}
			},function error(err){
				console.log(err);
			});	
		}
		$timeout(function () {
            rolesupdate();
        }, 1500);
	}	
	
	
		
	
	$scope.setroleId = function($event, $index){
		$scope.roleIdto =  $scope.tabVal[$index].roleId;
		console.log($scope.roleIdto );
		$state.go("uesr.role",{},{reload:true}); 
		$cookieStore.put('roleIdcookie',$scope.roleIdto);
		$("#roleby").modal("show");
		
	}
	
	// reload table
    function reloadTable() {
        $timeout(function() {
            $scope.paginationConf.onChange();
            $scope.master = false;
        },1500);
    };
}])
});